package com.qs.javame.thread.join;

/**
 * 测试：自定义实现join，并让线程的执行顺序为：threadA->threadB->main
 */
public class TestJoin4 {
    public static void main(String[] args) {
        MyThread threadA = new ThreadA();
        //构建线程B，并且线程B总是在线程A执行结束后在执行
        MyThread threadB = new ThreadB(threadA);

        threadA.start();
        threadB.start();

        /**
         * 主线程等待threadB执行完成后，再开始执行
         *
         * 注意：如果测试中断，这里需要调用 mainThread.interrupt()
         */
        try {
            threadB.myJoin();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main线程执行结束~");
    }

    public static void test() {
        MyThread threadA = new ThreadA();
        MyThread threadB = new ThreadB();
        threadA.start();
        threadB.start();
        System.out.println("main线程执行结束~");
    }

    //定义线程A
    static class ThreadA extends MyThread {

        private MyThread thread;

        public ThreadA() {

        }

        public ThreadA(MyThread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            try {
                //thread线程执行完，当前线程才开始执行
                if (thread != null) {
                    System.out.println(Thread.currentThread().getName() + "-执行myJoin()...1");
                    thread.myJoin();
                }

                //线程任务
                taskA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void taskA() {
            System.out.println(Thread.currentThread().getName() + "-执行ThreadB的线程任务taskA()...");
        }
    }


    //定义线程B
    static class ThreadB extends MyThread {

        private MyThread thread;

        public ThreadB() {

        }

        public ThreadB(MyThread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            try {
                //thread线程执行完，当前线程才开始执行
                if (thread != null) {
                    thread.myJoin();
                }

                //线程任务
                taskB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void taskB() {
            System.out.println(Thread.currentThread().getName() + "-执行ThreadB的线程任务taskB()...");
        }
    }


    static class MyThread extends Thread {

        //自定义join方法
        public synchronized void myJoin() throws InterruptedException {
            while (this.isAlive()) {
                /**
                 * wait会释放锁，阻塞等待（什么时候被notify?）
                 *
                 * 仔细分析：这里的锁对象是上一个运行的线程对象thread，而notify操作由jvm底层实现，当一个线程任务执行完，
                 * 会执行lock.notify_all(thread)，也就是唤醒在锁对象thread上的所有线程
                 */
                wait();
                System.out.println(Thread.currentThread().getName() + "-线程被唤醒了~");
            }

        }
    }
}






